package com.fjwt.gz.coupon.gtpay;

import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSONObject;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.third.bo.AwardCouponBo;
import com.fjwt.gz.coupon.SelfOperatedCouponsImpl;
import com.fjwt.gz.coupon.gtpay.demo.RSAUtilSegment;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Service;

import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import static com.fjwt.gz.core.utils.DESUtil.DES_KEY;
import static com.fjwt.gz.core.utils.DESUtil.encrypt;
import static com.fjwt.gz.core.utils.DESUtil.decrypt;
import static com.fjwt.gz.coupon.gtpay.demo.MktSignUtil.createSign;
import static com.fjwt.gz.coupon.gtpay.demo.RSAUtilSegment.gt;

@Service
@Slf4j
public class GtCreateCouponService implements SelfOperatedCouponsImpl {

    public static String gtKey = "Dl0AG8wdp45F";

    //创建商户
    public JSONObject instmch(String outMrchNo, String mrchPhone) throws Exception {

        JSONObject bodys = new JSONObject();
        bodys.put("outMrchNo", outMrchNo);
        bodys.put("mrchPhone", mrchPhone);
        HttpResponse response = null;
        String encryptStr = encrypt(DES_KEY, String.valueOf(bodys));
        try {
            HttpRequest body = HttpRequest.post("https://mktcldxylmyxrhgw.postar.cn/h5font/public/api/mrchList")
                    .header("Content-Type", "application/json;charset=UTF-8")
                    .timeout(10000)
                    .body(encryptStr);
            response = body.execute();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("网络连接异常,请稍后重试");
        }

        if (response == null) {
            throw new BizException("网络连接异常,请稍后重试");
        }
        String a = response.body();
        if (a != null && a.length() >= 2 && a.startsWith("\"") && a.endsWith("\"")) {
            a = a.substring(1, a.length() - 1);
        }
        String decrypt = decrypt(DES_KEY, a);
        JSONObject respData = JSONObject.parseObject(decrypt);
        log.info("响应结果：{}", respData);

        String message = MapUtil.getStr(respData,"message");

        if ("200".equals(MapUtil.getStr(respData, "code"))) {
            return respData;
        } else {
            throw new BizException(message);
        }

    }

    //创建发券
    public JSONObject response(AwardCouponBo awardCouponBo, String outRequestNo) throws Exception {

        JSONObject bodys = addAssemble(awardCouponBo, outRequestNo);
        HttpResponse response = null;
        JSONObject json = new JSONObject();
        log.info("请求参数：{}", bodys);
        json.put("url", "https://api.mch.weixin.qq.com/v3/marketing/favor/coupon-stocks");
        json.put("method", "POST");
        json.put("body", bodys);
        json.put("channelNo", "20250331095656498");
        String sign = createSign(com.alibaba.fastjson.JSONObject.parseObject(String.valueOf(json)), gtKey);
        json.put("sign", sign);
        String encryptStr = new String(Base64.encodeBase64(RSAUtilSegment.encryptByPublicKey(String.valueOf(json).getBytes(), gt)));

        try {
            HttpRequest body = HttpRequest.post("https://mktcldxylmyxrhgw.postar.cn/h5font/public/api/restWxInterface")
                    .header("Content-Type", "application/json;charset=UTF-8")
                    .timeout(10000)
                    .body(encryptStr);
            response = body.execute();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("网络连接异常,请稍后重试");
        }

        if (response == null) {
            throw new BizException("网络连接异常,请稍后重试");
        }
        JSONObject respData = JSONObject.parseObject(response.body());
        log.info("响应结果：{}", response);

        String message = MapUtil.getStr(respData,"message");

        if (MapUtil.getStr(respData,"stock_id") != null) {
            return respData;
        } else {
            throw new BizException(message);
        }

    }

    //激活自主发券
    public String activationResponse(String stockId) throws Exception {

        HttpResponse response = null;
        JSONObject json = new JSONObject();
        String url = "https://api.mch.weixin.qq.com/v3/marketing/favor/stocks/" + stockId + "/start";
        json.put("url", url);
        json.put("method", "POST");
        String bodys = "{\t\t\n" +
                "\t     \"stock_creator_mchid\": \"1501970731\",\n" +
                "    }\n";
        JSONObject jsonObject = JSONObject.parseObject(bodys);
        json.put("body", jsonObject);
        json.put("channelNo", "20250331095656498");
        String sign = createSign(com.alibaba.fastjson.JSONObject.parseObject(String.valueOf(json)), gtKey);

        json.put("sign", sign);
        String encryptStr = new String(Base64.encodeBase64(RSAUtilSegment.encryptByPublicKey(String.valueOf(json).getBytes(), gt)));

        try {

            HttpRequest body = HttpRequest.post("https://mktcldxylmyxrhgw.postar.cn/h5font/public/api/restWxInterface")
                    .header("Content-Type", "application/json;charset=UTF-8")
                    .timeout(10000)
                    .body(encryptStr);
            response = body.execute();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("网络连接异常,请稍后重试");
        }

        if (response == null) {
            throw new BizException("网络连接异常,请稍后重试");
        }
        JSONObject respData = JSONObject.parseObject(response.body());
        log.info("响应结果：{}", response);
        if (MapUtil.getStr(respData,"stock_id") != null) {
            return "success";
        } else {
            log.info("响应结果：{}", MapUtil.getStr(respData,"message"));
            return MapUtil.getStr(respData,"message");
        }

    }

    //发放卡券
    public JSONObject openidResponse(JSONObject bodys,String openId) throws Exception {
//1501970731202503131349696989700292608
        HttpResponse response = null;
        JSONObject json = new JSONObject();
        String url = "https://api.mch.weixin.qq.com/v3/marketing/favor/users/" + openId + "/coupons";
        json.put("url", url);
        json.put("channelType", "D12");
        json.put("method", "POST");
        json.put("body", bodys);
        json.put("channelNo", "20250331095656498");
        log.info("请求参数：{}", json);
        String sign = createSign(com.alibaba.fastjson.JSONObject.parseObject(String.valueOf(json)), gtKey);

        json.put("sign", sign);
        String encryptStr = new String(Base64.encodeBase64(RSAUtilSegment.encryptByPublicKey(String.valueOf(json).getBytes(), gt)));
        try {

            HttpRequest body = HttpRequest.post("https://mktcldxylmyxrhgw.postar.cn/h5font/public/api/restWxInterface")
                    .header("Content-Type", "application/json;charset=UTF-8")
                    .timeout(10000)
                    .body(encryptStr);
            response = body.execute();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("网络连接异常,请稍后重试");
        }

        if (response == null) {
            throw new BizException("网络连接异常,请稍后重试");
        }
        JSONObject respData = JSONObject.parseObject(response.body());
        log.info("响应结果：{}", response);
        if (MapUtil.getStr(respData,"coupon_id") != null) {
            return respData;
        } else {
            if (MapUtil.getStr(respData,"message") != null){
                throw new BizException(MapUtil.getStr(respData,"message"));
            }else {
                throw new BizException("网络波动请联系管理员");
            }
        }

    }

    //创建发券
    public JSONObject mchinfo(JSONObject jsonObject) throws Exception {

        HttpResponse response = null;
        String sign = createSign(com.alibaba.fastjson.JSONObject.parseObject(String.valueOf(jsonObject)), gtKey);
        jsonObject.put("sign", sign);
        String encryptStr = new String(Base64.encodeBase64(RSAUtilSegment.encryptByPublicKey(String.valueOf(jsonObject).getBytes(), gt)));

        try {
            HttpRequest body = HttpRequest.post("https://mktcldxylmyxrhgw.postar.cn/h5font/public/api/mrchList")
                    .header("Content-Type", "application/json;charset=UTF-8")
                    .timeout(10000)
                    .body(encryptStr);
            response = body.execute();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("网络连接异常,请稍后重试");
        }

        if (response == null) {
            throw new BizException("网络连接异常,请稍后重试");
        }
        JSONObject respData = JSONObject.parseObject(response.body());
        log.info("响应结果：{}", response);

        String message = MapUtil.getStr(respData,"message");

        if (MapUtil.getStr(respData,"code").equals("200")) {
            return  JSONObject.parseObject(MapUtil.getStr(respData,"data"));
        } else {
            throw new BizException(message);
        }

    }


    //数据组装
    public JSONObject addAssemble(AwardCouponBo awardCouponBo, String outRequestNo) {
        JSONObject json = new JSONObject();

        json.put("stock_type", "NORMAL"); //批次类型
        JSONObject coupon_use_rule = new JSONObject(); //核销规则

        coupon_use_rule.put("combine_use", false); //是否可叠加其他优惠
        List<String> available_merchants = new ArrayList<>(); //可用商户号
        available_merchants.add(awardCouponBo.getWechatSubmerchantNo());//TODO  注意这个是要修改的，目前没有传进来商户号
        coupon_use_rule.put("available_merchants", available_merchants);

        JSONObject fixed_normal_coupon = new JSONObject(); //固定面额满减券使用规则
        fixed_normal_coupon.put("coupon_amount", awardCouponBo.getCouponPrice()); //面额 (分)
        fixed_normal_coupon.put("transaction_minimum", awardCouponBo.getPayAmount()); //门槛
        coupon_use_rule.put("fixed_normal_coupon", fixed_normal_coupon);

        json.put("coupon_use_rule", coupon_use_rule);
        json.put("no_cash", true); //营销经费。枚举值：true：免充值false：预充值

        JSONObject stock_use_rule = new JSONObject(); //发放规则
        stock_use_rule.put("prevent_api_abuse", true); //是否开启防刷拦截
        stock_use_rule.put("max_amount_by_day", awardCouponBo.getCouponNum() * awardCouponBo.getCouponPrice()); //单天预算发放上限
        stock_use_rule.put("natural_person_limit", true); //是否开启自然人限制
        stock_use_rule.put("max_amount", awardCouponBo.getCouponNum() * awardCouponBo.getCouponPrice()); //总预算
        stock_use_rule.put("max_coupons_per_user", awardCouponBo.getEveryoneMaxNum()); //单个用户可领个数
        stock_use_rule.put("max_coupons", awardCouponBo.getCouponNum()); //发放总上限

        json.put("stock_use_rule", stock_use_rule);
        json.put("stock_name", awardCouponBo.getCouponName()); //券名称
        json.put("available_end_time", awardCouponBo.getEndTime().toInstant().atZone(ZoneId.of("Asia/Shanghai")).format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX"))); //可用时间-结束时间
        json.put("comment", ""); //备注

        JSONObject pattern_info = new JSONObject(); //样式设置
        pattern_info.put("description", "1.本券自用户领取后立即生效，不可拆分，不可找零，不得提现，无法转赠。\\n2、如您使用优惠券的订单成功退款后，订单所用优惠券将会返回至您的账户，届时请您及时查看。退还后的优惠券有效期不变，如退还时优惠券已过期，则过期不补。\\n3、付款方式仅支持微信支付。\\n4、本活动具体使用如有不明处，请联系发券商户。");

        json.put("pattern_info", pattern_info);
        json.put("belong_merchant", "1501970731"); //归属商户号
        json.put("out_request_no", outRequestNo); //商户单据号
        json.put("available_begin_time", awardCouponBo.getStartTime().toInstant().atZone(ZoneId.of("Asia/Shanghai")).format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX"))); //可用时间-开始时间

        return json;
    }

}
